// pages/parcel_detail/index.js
var app = getApp();
const recorderManager = wx.getRecorderManager();//录音管理
// const innerAudioContext = wx.createInnerAudioContext();//播放音频
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cashbox: '', //自己领取的钱
    open_mouse: 0, //领取状态
    istrue: true,
    redid: 0,
    Participant: [],
    udata: [],
    redpack: [],
    getback:0, //退回多少钱
    j: 1,//帧动画初始图片 
    isSpeaking: false,//是否正在说话 
    voices: [],//音频数组 
    i: 0,
    // 判断用户的点击
    user_click: true,
    user_click_index: '',
  },

  //手指按下
  touchdown: function (e) {
    console.log("手指按下了...")
    console.log("new date : " + new Date)
    var _this = this;
    speaking.call(this);
    console.log(speaking.call);
    this.setData({
      isSpeaking: true
    })
    console.log('开始录音');
    //录音start
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    const options = {
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 72000,
      format: 'mp3',
      frameSize: 50
    }
    recorderManager.start(options);
    //end
  },

  //手指抬起 
  touchup: function () {
    console.log("手指抬起了...")
    this.setData({
      isSpeaking: false,
    })
    clearInterval(this.timer);
    //录音停止
    recorderManager.stop();
    //录音停止事件
    recorderManager.onStop((res) => {
      wx.showLoading({ title: '正在拼命抢', mask: true })
      console.log('recorder stop', res)
      const { tempFilePath } = res.tempFilePath;
      var that = this;
      var redid = that.data.redid;
      var aaa = parseInt(res.duration / 1000);
      wx.uploadFile({
        // url: 'https://hd.huwaishequ.com/red/public/voiceUpload', //录音接口
        url: app.url2 + 'api/voiceUpload', //录音接口
        filePath: res.tempFilePath,
        header: { "Content-Type": "multipart/form-data" },
        name: "file",
        formData: {
          'redid': redid,
          'openid': wx.getStorageSync('openid'),
          'duration': aaa,
          'token': wx.getStorageSync('token_md5'),          
        },
        success: function (res) {//录音返回结果
          wx.hideLoading();
          var data = res.data
          console.log(res);
          if (data == '1002') {//上传或转码失败
            filing('录音的姿势不对','loading');
          } else if (data == '1001') {//识别失败
            filing('匹配失败', 'loading');
          } else if (data == '1000') {//领取完
            filing('被领完了', 'loading');
          } else {//匹配成功，领取
            filing('领取成功!', 'success');
            var Participant = that.data.Participant;
            var kdata = JSON.parse(data);
            kdata.istrue = true;
            kdata.price = kdata.price.toFixed(2);
            kdata.created_at = (getLocalTime(kdata.created_at));
            var redpack = that.data.redpack;
            redpack.s_number--;
            Participant.push(kdata);
            that.setData({
              cashbox: kdata.price,
              open_mouse: 2,
              Participant: Participant,
              redpack: redpack,
            });
            console.log(Participant);
          }
        },
        fail: function (res) {//上传失败
          console.log(res);
        },
      })

    })

    //录音错误
    recorderManager.onError((res) => {
      console.log(res);
      filing('录音时间太短了', 'loading');
    })
  },

  //点击播放录音 
  gotoPlay: function (e) {
    var that = this;
    var Participant = that.data.Participant;//获取好友列表
    var index = e.currentTarget.dataset.index;//获取被点击的好友下标

    if (Participant[index].istrue) {

      // 更改状态显示    
      state(that, Participant, index, false);

      that.innerAudioContext.onError((res) => { console.log(res); })// 播放音频失败的回调
      that.innerAudioContext.src = e.currentTarget.dataset.key; // 这里可以是录音的临时路径
      that.innerAudioContext.play();
      //音频自然播放结束事件
      that.innerAudioContext.onEnded((res) => {
        // 更改状态显示
        state(that, Participant, index, true)
      })
    } else {
      // 更改状态显示
      state(that, Participant, index, true)

      //音频停止事件
      console.log('音频停止事件');
      that.innerAudioContext.stop()
      that.setData({
        click_aaa: 0,
        innerAudioContext: wx.createInnerAudioContext(),
      })

    }



    // 更改状态显示
    function state(that, all, index, text) {
      for (var i in Participant) {
        Participant[i].istrue = true;
      }
      all[index].istrue = text;
      that.setData({
        Participant: all,
      })
    }
  },


//投诉
  complaints:function(e){
    var that=this;
    wx.navigateTo({
      url: '/pages/voice_box/complaints/index?id=' + that.data.redid,
    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.innerAudioContext = wx.createInnerAudioContext();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
    console.log(options);
    console.log('我在这~~~~！！！！');
    // wx.setStorage({ key: "id", data: options.id })//缓存id
    that.setData({ redid: (options.id ? options.id : options.scene) });
    if (wx.getStorageSync('openid') == '') {
      app.app_load(that.log_load);
    } else {
      that.log_load();
    }
    wx.hideLoading();                            
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success(res) {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              // wx.startRecord()
              console.log(res);
            }
          })
        }
      }
    })
  },
  // 登录后加载
  log_load: function (e,c) {
    var that = this;
    var openid = wx.getStorageSync('openid');
    if (openid == '' || openid == null) {
      openid = c;
    }
    console.log('openid:', wx.getStorageSync('openid'));
    console.log('redid:', that.data.redid);
    wx.showLoading({ title: 'loading', mask: true });
    app.token_md5();                       
    //加载音频
    wx.request({
      // url: app.url2 + 'api/voiceLoad', //录音接口
      url: app.url2 + 'api/voiceLoad', //录音接口
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        redid: that.data.redid,
        openid: openid,
        token: wx.getStorageSync('token_md5'),
      },
      method: 'GET',
      success: function (res) {
        var data = res.data;
        console.log(data);
        var money_number = data.data.price;
        data.data.price = money_number.toFixed(2);
        // 时间转化
        for (var i in data.vdata) {
          data.vdata[i].created_at = (getLocalTime(data.vdata[i].created_at));
          data.vdata[i].istrue = true;
          data.vdata[i].price = data.vdata[i].price.toFixed(2);
        }
        var num_money = data.cashbox;
        data.cashbox = Number(num_money).toFixed(2);

        data.data.password=data.data.password.split('');
        console.log(data.data.password);

        that.setData({
          Participant: data.vdata,
          udata: data.udata,
          redpack: data.data,
          getback: data.getback,
          open_mouse: data.open_mouse,
          cashbox: data.cashbox,
          code_url: data.code_url,
        })
        console.log(that.data.code_url);
        wx.hideLoading();                        
        
      },

    });

    this.wallet(c);
  },

  wallet: function (e) {
    console.log(wx.getStorageSync('openid'));
    wx.showLoading({ title: 'loading', mask: true })
    var that = this;
    var openid = wx.getStorageSync('openid');
    if (openid == '' || openid == null) {
      openid = e;
    }
    app.token_md5();
    wx.request({
      url: app.url2 + 'api/camelUserLogin',
      data: {
        openid: openid,
        token: wx.getStorageSync('token_md5'),
      },
      header: { 'content-type': 'application/json' },
      success: function (res) {

      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading({ title: '加载中', mask: true });        
    var that=this;
    console.log('下拉刷新开始···');
    app.token_md5();
    wx.request({
      // url: app.url2 + 'api/voiceLoad',
      url: app.url2 + 'api/voiceLoad',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        redid: that.data.redid,
        openid: wx.getStorageSync('openid'),
        token: wx.getStorageSync('token_md5'),
      },
      method: 'GET',
      success: function (res) {
        wx.hideLoading();
        var data = res.data;
        console.log(data);
        var money_number = data.data.price;
        data.data.price = money_number.toFixed(2);
        // 时间转化
        for (var i in data.vdata) {
          data.vdata[i].created_at = (getLocalTime(data.vdata[i].created_at));
          data.vdata[i].istrue = true;
          data.vdata[i].price = data.vdata[i].price.toFixed(2);
        }
        var num_money = data.cashbox;
        data.cashbox = Number(num_money).toFixed(2);

        that.setData({
          Participant: data.vdata,
          udata: data.udata,
          redpack: data.data,
          getback: data.getback,
          open_mouse: data.open_mouse,
          cashbox: data.cashbox,
          code_url: data.code_url,
        })
        wx.stopPullDownRefresh()
        wx.hideLoading();                    
        console.log('下拉刷新结束···');
        prompt('刷新成功', 'success')
      },
      fail: function (res) {
        console.log(res.data)
        wx.hideLoading();                            
        //提示信息
        prompt('加载失败', 'loading')
      },
    });
  }

})

//麦克风帧动画 
function speaking() {
  var _this = this;
  //话筒帧动画 
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}

function filing(text,state) {
  wx.showToast({
    title: text,
    icon: state,
    duration: 1000,
    mask: true
  })
}

// 日期计算
function getLocalTime(nS) {
  var Y, M, D, W, H, I, S;
  function fillZero(v) {
    if (v < 10) { v = '0' + v; }
    return v;
  }
  var d = new Date(parseInt(nS) * 1000);
  M = fillZero(d.getMonth() + 1);
  D = fillZero(d.getDate());
  H = fillZero(d.getHours());
  I = fillZero(d.getMinutes());
  var localTime = M + '月' + D + '日 ' + H + ':' + I;
  return localTime;
}

// 提示信息
function prompt(text, status){
  wx.showToast({
    title: text,
    icon: status,
    duration: 1200,
  }) 
}